//
//  SEGWKWebViewLoadController.m
//  SEGStandard
//
//  Created by 山刘 on 2020/3/16.
//

#import "SEGWKWebViewLoadController.h"
#import "SEGUrlparamsModel.h"
#import "SEGWebViewLoadManager.h"
#import "SEGSystemnativeModel.h"
#import "SEGDocument.h"

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif


@interface SEGWKWebViewLoadController ()<UIDocumentMenuDelegate ,UIDocumentPickerDelegate,SEGImagePickerManagerDelegate,UIActionSheetDelegate>
@property (nonatomic, strong) SEGImagePickerManager *imagePicker;
@end

@implementation SEGWKWebViewLoadController{
    //设置最大图片数
    NSInteger maxPhoto;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - 私有方法

-(void)segAddNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil];
}

- (void)getOrderPayResult:(NSNotification*)notification {
    if ([notification.object isEqualToString:@"success"]) {
        [self loadCbUrlString];
    }
}


/**
 使用相机、相册
 */
-(void)seg_UsePhotoAlbumAndCamera{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机选择",@"相机",nil];
    [actionSheet showFromTabBar:self.navigationController.tabBarController.tabBar];
}



/**
 唤起相机功能
 */
-(void)seg_UseCamera{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {//判断是否有相机
        self.imagePicker = [[SEGImagePickerManager alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
        self.imagePicker.allowsEditing = NO;
        [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
    }
    else {
        [[[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备无摄像头" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
    }
}


/**
 唤起系统相册功能
 */
-(void)seg_UsePhotoAlbum:(NSInteger)number{
    self.imagePicker = [[SEGImagePickerManager alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
    self.imagePicker.allowsEditing = NO;
    self.imagePicker.maxImagesCount = number;
    [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
}

-(void)saveImageToLocal:(NSArray<UIImage*>*)data{
    
    __block NSMutableArray<NSDictionary*>* tmp = [NSMutableArray array];
    [data enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *imageData = [obj adjustImageWithinLenght:1*1024*1024];//图片控制在1M
        NSString *fileName = [NSString stringWithFormat:@"WebTmpImage_%@_%zd.jpg",[NSDate getCurrentTimeTimestamp:SEGEnumTimerstamp_MilliSecond],idx];
        NSString* imageLocalPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
        [imageData writeToFile:imageLocalPath atomically:YES];
        
        [tmp addObject:@{@"uri":imageLocalPath, @"base64":[imageData base64EncodedString]}];
    }];
    
    if (tmp.count <= 0) return;
    
    NSDictionary *params = @{
        @"code": @"1",
        @"message": @"",
        @"data": tmp//图片base64 string
    };
    
    SEGUrlparamsModel * js = [SEGUrlparamsModel yy_modelWithJSON:[[self.current_uhomeoc_href.query stringByURLDecode] stringByReplacingOccurrencesOfString:@"params=" withString:@""]];
    NSString *javaScript = [NSString stringWithFormat:@"%@(%@);",js.fn,[params yy_modelToJSONString]];
    [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

#pragma mark - JS交互
-(void)segJSBusinessOpenActDetailWithQuery:(NSString*)query{
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    for (NSString *object in [query componentsSeparatedByString:@"&"]) { //[@"key=value",@"key=value",...]
        NSString *key = [[object componentsSeparatedByString:@"="] firstObject];
        NSString *value = [[object componentsSeparatedByString:@"="] lastObject];
        [data setValue:value forKey:key];
    }
    
    NSDictionary *params = @{@"serviceId":data[@"id"]};
    UIViewController *GroupsShoppingDetailVC = [[SEGUhomeMediator sharedInstance] seg_initGroupsShoppingDetailViewController:params];
    [self.navigationController pushViewController:GroupsShoppingDetailVC animated:YES];
}

-(void)segJSHomeserviceCounselingWithQuery:(NSString*)query{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    NSString* goMessage = [NSString stringWithFormat:@"100888|%@|%@|%@|%@", data.providerSid , data.serviceSid, data.type, kAccountUserID];
    
    NSDictionary *params = @{@"groupID":goMessage};
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initOrderMessageViewController:params];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)segJSHomeserviceConfirmOrderWithQuery:(NSString*)query {
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    NSDictionary *params = @{@"dataDic":[ data yy_modelToJSONObject]};
    UIViewController *OrderComfirmVC = [[SEGUhomeMediator sharedInstance] seg_initOrderComfirmViewController:params];
    [self.navigationController pushViewController:OrderComfirmVC animated:YES];
}

-(void)segJSUserInfoGetWithQuery:(NSString*)query{
    NSString *jsString = [SEGWebViewLoadManager segJavaScriptStringFromUrlString:query];
    NSLog(@"%@",jsString);
    if (jsString && jsString.length > 0) {
        [self.webView evaluateJavaScript:jsString completionHandler:^(id _Nullable req, NSError * _Nullable error) {
        }];
    }
}

-(void)segJSSystemOpenImgViewerWithQuery:(NSString*)query{
    [[[UIAlertView alloc]initWithTitle:@"提示" message:@"此功能暂时不支持！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
}

-(void)segJSSystemJumpToNativeWithQuery:(NSString*)query {
    SEGSystemnativeModel * data = [SEGSystemnativeModel yy_modelWithJSON:query];
    
    NSString *page = data.page; //跳转页面code
    NSDictionary *paraDict = [data.para yy_modelToJSONObject];//跳转页面参数
    
    //积分页面
    if ([page isEqualToString:@"MY_POINT"]) {
        
        NSDictionary *params = @{@"banalceType":([paraDict objectForKey:@"balanceType"])};
        UIViewController *IntegralCashVC = [[SEGUhomeMediator sharedInstance] seg_initIntegralCashViewController:params];
        [self.navigationController pushViewController:IntegralCashVC animated:YES];
        return;
    }
    
    //积分商城订单确认
    if ([page isEqualToString:@"BONUSES_ORDER_CONFIRM"]) {
        
        NSDictionary *params = @{@"idString":ValueToString([paraDict objectForKey:@"id"])};
        UIViewController *VC = [[SEGUhomeMediator sharedInstance]seg_initIntegralExchangeConfirmViewController:params];
        [self.navigationController pushViewController:VC animated:YES];
        return;
    }
    
    //广告页面
    if ([page isEqualToString:@"ADVERTISEMENT"]) {
        //发送广告跳转通知
        NSDictionary* dict = @{
            @"typeId" : ValueToString([paraDict objectForKey:@"typeId"]),
            @"href" : ValueToString([paraDict objectForKey:@"href"]),
            @"title" : ValueToString([paraDict objectForKey:@"title"])
        };
        [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithType:dict];
        return;
    }
    
    //住户好评
    if ([page isEqualToString:@"FIVE_STAR_RATING"]) {
        NSDictionary* dict = @{
            @"type" : @"0",
            @"action" : @"cn.segi.uhome.action.FIVESTAR"
        };
        [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
        
        return;
    }
    
    //优秀员工
    if ([page isEqualToString:@"GOOD_STAFF"]) {
        NSString *introId = [paraDict valueForKey:@"introId"];
        NSDictionary* dict = @{
            @"type" : @"0",
            @"action" : @"cn.segi.uhome.action.GOODSTAFF",
            @"introId" : ValueToString(introId)
        };
        [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
        return;
    }
    
    //便民
    if ([page isEqualToString:@"CONVENIENCE_SERVICE"]) {
        NSDictionary* dict = @{
            @"type" : @"0",
            @"action" : @"cn.segi.uhome.action.PAGE"
        };
        [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
        return;
    }
    
    //商圈
    if ([page isEqualToString:@"BUSINESS_SERVICE"]) {
        NSDictionary* dict = @{
            @"type" : @"0",
            @"action" : @"cn.segi.uhome.action.BUSINESS_CIRCLE"
        };
        [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
        return;
    }
    
    //数字社区
    if ([page isEqualToString:@"ASSETS_AUTHENTICATION"]) {
        UIViewController *VC = [[SEGUhomeMediator sharedInstance]seg_initDigitalComRootViewController:nil];
        [self.navigationController pushViewController:VC animated:YES];
        
        return;
    }
}

-(void)segJSSystemUploadFilesWithQuery:(NSString*)query request:(NSURL*)request{
    SEGSystemnativeModel * data = [SEGSystemnativeModel yy_modelWithJSON:query];
    __block NSMutableArray<NSData*> *paramsDataArrM = [NSMutableArray array];
    __block NSMutableArray<SEGUploadFileModel *> *fileModelArr = [NSMutableArray array];
    __block BOOL isImage;
    [data.para.uri enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray * stringType = [obj componentsSeparatedByString:@"."];
        NSString * type = stringType.lastObject;
        type = type.lowercaseString;
        if ([type isEqualToString:@"bmp"] || [type isEqualToString:@"jpg"] || [type isEqualToString:@"jpge"] || [type isEqualToString:@"png"] || [type isEqualToString:@"gif"]){
            isImage = YES;
            NSData *localData = [NSData dataWithContentsOfFile:obj];
            if (localData) [paramsDataArrM addObject:localData];
        }else {
            isImage = NO;
            SEGUploadFileModel *model = [SEGUploadFileModel new];
            model.data = [NSData dataWithContentsOfFile:obj];
            model.fileName = obj;
            model.mimeType = @"application/octet-stream";
            [fileModelArr addObject:model];
        }
    }];
    
    if (isImage) {
        if (paramsDataArrM.count <=0) {
            NSString *javaScript = [NSString stringWithFormat:@"%@(%@)",data.fn,[@{@"code":@"0",@"message":@"本地不存在图片缓存，请重新上传！",@"data":@""} yy_modelToJSONString]];
            [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
            }];
            return;
        }
        //图片上传到服务器
        //[SVProgressHUD show]; 有的网页有loading，有的没有loading，这个不好加
        [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithData:paramsDataArrM serviceType:data.para.serviceType progress:^(double progressValue) {
        } completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            //[SVProgressHUD dismiss];
            if (!isSuccessed) {
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
            }
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setValue: isSuccessed ? @"1" : @"0" forKey:@"code"];
            [params setValue:[SEGMultipartfileuploadManager sharedManager].multipartFileUpload.message forKey:@"message"];
            if ([SEGMultipartfileuploadManager sharedManager].multipartFileUpload.data.count > 0) {
                [params setValue:@{@"urls":[SEGMultipartfileuploadManager sharedManager].multipartFileUpload.data} forKey:@"data"];
                NSString *javaScript = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                }];
            }
        }];
    }else {
        //其他文件上传到服务器
        if (fileModelArr.count <= 0) {
            return;
        }
        __weak typeof (self) weakSelf = self;
        //[SVProgressHUD show]; 有的网页有loading，有的没有loading，这个不好加
        [[SEGUploadmultipartfileManager sharedManager] requestDatasWithDetailData:fileModelArr progress:^(double progressValue) {
        } completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            //[SVProgressHUD dismiss];
            if (!isSuccessed) {
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
            }
            SEGUploadmultipartfileModel *model = [SEGUploadmultipartfileManager sharedManager].uploadMultipartFile;
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setValue: isSuccessed ? @"1" : @"0" forKey:@"code"];
            [params setValue:model.message forKey:@"message"];
            if (model.data.count > 0) {
                [params setValue:@{@"urls":model.data} forKey:@"data"];
                NSString *javaScript = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                [weakSelf.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                    
                }];
            }
        }];
    }
}

-(void)segJSSystemSocialShareWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    NSString *imageUrl = [NSString stringWithFormat:@"%@%@",kClientImageRootURL,data.icon];
    NSDictionary *parsma = @{
        @"sharetitle": data.title,
        @"sharecontent": data.content,
        @"shareTypesArrType":@"1",
        @"inviteurl": data.url,
    };
    NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:parsma];
    if (data.icon && data.icon.length > 0) [tmp setValue:imageUrl forKey:@"shareImageUrlString"];
    
    UIViewController* shareVC = [[SEGUhomeMediator sharedInstance] seg_initShareViewController:tmp actionType:^(NSInteger actionType) {
        
    } channel:^(NSString *channel) {
        
    }];
    [self presentViewController:shareVC animated:NO completion:^{
    }];
}

- (void)segJSThirdpartyMiniProgramWithQuery:(NSString*)query {
    
    NSData *jsonData = [query dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if (err) {
        NSLog(@"json解析失败：%@",err);
        [SVProgressHUD showInfoWithStatus:err.localizedDescription];
        return ;
    }
    
    [[SEGUhomeMediator sharedInstance] seg_initMiniProgram:dic];
}

/**
 签名
 */
-(void)segJSSystemSignatureWithQuery:(NSString*)query request:(NSURL*)request image:(UIImage*)image{
    SEGUrlparamsModel * urlData = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    NSData *imageData = [image adjustImageWithinLenght:1*1024*1024];//图片控制在1M
    NSString* imageLocalPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Signature.jpg"];
    [imageData writeToFile:imageLocalPath atomically:YES];
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:[imageData base64EncodedString] forKey:@"base64"];
    [data setValue:imageLocalPath forKey:@"uri"];
    
    NSString *string = [NSString stringWithFormat:@"%@(%@)",urlData.fn,[@{@"code":@"1",@"message":@"",@"data":data} yy_modelToJSONString]];
    [self.webView evaluateJavaScript:string completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

-(void)segJSSystemTakeFilesWithQuery:(NSString*)query request:(NSURL*)request{
    UIDocumentMenuViewController * importMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
    importMenu.delegate = self;
    importMenu.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:importMenu animated:YES completion:nil];
}

-(void)segJSThirdpartyPayWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];

    //字符串转字典
    NSDictionary *param = @{
        @"payTypeName": @(SEGPayTypeName_CMHK_PayOnLine),
        @"dict": [data.payInfo yy_modelToJSONObject],
        @"payCode": data.payCode,
        @"cbUrl": data.cbUrl
    };
    [[SEGUhomeMediator sharedInstance] seg_initPayListViewController:param];
    
    [self segAddNotifications];
}

-(void)segJSThirdpartyGoPayListWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    NSDictionary *param = @{
        @"payTypeName": @(SEGPayTypeName_QiaoChengHui),
        @"dict":[data yy_modelToJSONObject]
    };
    UIViewController *payListVC = [[SEGUhomeMediator sharedInstance]seg_initPayListViewController:param];
    payListVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:payListVC animated:YES];
}

-(void)segJSThirdpartyOpenDialogWithQuery:(NSString*)query{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    UIAlertView *alert;
    if ([data.type isEqualToString:@"1"]) {
        alert = [[UIAlertView alloc] initWithTitle:data.title message:data.content delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    }else if ([data.type isEqualToString:@"2"]){
        alert = [[UIAlertView alloc] initWithTitle:data.title message:data.content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    }else{
        alert = [[UIAlertView alloc] initWithTitle:data.title message:data.content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    [alert show];
}

-(void)segJSSystemCameraWithQuery:(NSString*)query request:(NSURL*)request{
    SEGSystemnativeModel * data = [SEGSystemnativeModel yy_modelWithJSON:query];
    
    if (data && [data.para.type isEqualToString:@"1"]) {//拍照
        [self seg_UseCamera];
        
    }else if (data && [data.para.type isEqualToString:@"2"]){//相册
        [self seg_UsePhotoAlbum:data.para.number.integerValue];
    }else{//拍照&相册
        maxPhoto = data.para.number.integerValue;
        [self seg_UsePhotoAlbumAndCamera];
    }
}



#pragma mark - <SEGWKWebViewController> 父类抽象方法
/// JS协议拦截
-(BOOL)jsInvokeSystemFunctionWithWebView:(WKWebView *)webView request:(NSURLRequest *)request query:(nonnull NSString *)query{
    NSString * host = request.URL.host;
    
    // 第三方使用api：拍照
    if ([host rangeOfString:@"thirdparty.takePhoto"].location != NSNotFound) {
        [self seg_UsePhotoAlbumAndCamera];
        return NO;
    }
    
    // 使用原生系统功能：相机
    if ([host rangeOfString:@"system.camera"].location != NSNotFound) {
        [self segJSSystemCameraWithQuery:query request:request.URL];
        return NO;
    }
    
    // 第三方使用api：跳转到支付列表
    if ([host rangeOfString:@"thirdparty.goPayList"].location != NSNotFound) {
        [self segJSThirdpartyGoPayListWithQuery:query request:request.URL];
        return NO;
    }
    
    // 第三方使用api：支付
    if ([host rangeOfString:@"thirdparty.pay"].location != NSNotFound) {
        [self segJSThirdpartyPayWithQuery:query request:request.URL];
        return NO;
    }
    
    // 使用原生系统功能：批量获取本地文件
    if ([host rangeOfString:@"system.takeFiles"].location != NSNotFound) {
        [self segJSSystemTakeFilesWithQuery:query request:request.URL];
        return NO;
    }

    // 使用原生系统功能：签名
    if ([host rangeOfString:@"system.signature"].location != NSNotFound) {
        @weakify(self)
        UIViewController *VC =  [[SEGUhomeMediator sharedInstance] seg_initSEGSignViewController:^(UIImage * image) {
            @strongify(self)
            [self segJSSystemSignatureWithQuery:query request:request.URL image:image];
        }];
        [self.navigationController pushViewController:VC animated:YES];
        return NO;
    }
    
    // 使用原生系统功能：退出登录
    if ([host rangeOfString:@"system.logout"].location != NSNotFound) {
        [[SEGHTTPManager sharedNetworkManager]removeCookies];//登录前清除cookies
        [[SEGHTTPManager sharedNetworkManager] segCancelAllRequest];
        [[SEGUhomeMediator sharedInstance]seg_pushToLoginViewController:nil];
        return NO;
    }
    
    //  第三方使用api：打开小程序
    if ([host rangeOfString:@"thirdparty.openWXMiniProgram"].location != NSNotFound) {
        [self segJSThirdpartyMiniProgramWithQuery:query];
        return NO;
    }
    
    // 使用原生系统功能：分享到社交平台
    if ([host rangeOfString:@"system.socialShare"].location != NSNotFound) {
        [self segJSSystemSocialShareWithQuery:query request:request.URL];
        return NO;
    }
    
    // 使用原生系统功能：批量上传文件
    if ([host rangeOfString:@"system.uploadFiles"].location != NSNotFound) {
        [self segJSSystemUploadFilesWithQuery:query request:request.URL];
        return NO;
    }
    
    // 使用原生系统功能：跳转到原生页面
    if ([host rangeOfString:@"system.jumpToNative"].location != NSNotFound) {
        [self segJSSystemJumpToNativeWithQuery:query];
        return NO;
    }
    // 使用原生系统功能：使用系统自带图片浏览器打开图片
    if ([host rangeOfString:@"system.openImgViewer"].location != NSNotFound) {
        [self segJSSystemOpenImgViewerWithQuery:query];
        return NO;
    }
    // 商业改造-打开商品详情
    if ([host rangeOfString:@"business.openActDetail"].location != NSNotFound){
        [self segJSBusinessOpenActDetailWithQuery:query];
        return NO;
    }
    // 客服跳转
    if ([host rangeOfString:@"homeservice.counseling"].location != NSNotFound){
        [self segJSHomeserviceCounselingWithQuery:query];
        return NO;
    }
    // 确认订单页跳转
    if ([host rangeOfString:@"homeservice.confirmOrder"].location != NSNotFound){
        [self segJSHomeserviceConfirmOrderWithQuery:query];
        return NO;
    }
    // 用户信息-获取用户信息
    if ([host rangeOfString:@"userInfo.get"].location != NSNotFound) {
        [self segJSUserInfoGetWithQuery:query];
        return NO;
    }
    return YES;
}
/// URL地址参数替换
-(NSString*)segReplaceUrlStringWithUrlString:(NSString *)urlString{
    return [SEGWebViewLoadManager segReplaceUrlStringWithUrlString:urlString];
}
/// URL地址添加平台号
-(NSString*)getUrlStringWithAppPlatformCode:(NSString *)urlString{
    return [SEGPlatformManager getUrlStringWithAppPlatformCode:urlString];
}

/// Web工具栏分享按钮的触发
/// @param query 数据从 homeservice.setSharePara 协议来
-(void)segShare:(NSString *)query{
    SEGUrlparamsModel *data = [SEGUrlparamsModel yy_modelWithJSON:query];
    if (!data) return;
    
    //拼接应用的scheme
    NSString *shareUrl;
    NSString *documentURL = self.currentUrl.absoluteString;
    
    if ([documentURL rangeOfString:@"?"].location == NSNotFound) {
        //没有任何参数时 用？拼接
        shareUrl = [NSString stringWithFormat:@"%@?scheme=%@",documentURL ,kOpenAppScheme];
    }else {
        shareUrl = [NSString stringWithFormat:@"%@&scheme=%@",documentURL,kOpenAppScheme];
    }
    shareUrl = [SEGPlatformManager getUrlStringWithAppPlatformCode:shareUrl];
    
    NSDictionary *parsma = @{
        @"sharetitle": data.title,
        @"sharecontent": [NSString stringWithFormat:@"我在%@发现了一个好东西，用积分就能兑换。",kAppName],
        @"inviteurl": shareUrl,
        @"shareTypesArrType":@"1",
    };
    NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:parsma];
    if (data.icon && data.icon.length > 0) [tmp setValue:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,data.icon] forKey:@"shareImageUrlString"];
    
    UIViewController* shareVC = [[SEGUhomeMediator sharedInstance] seg_initShareViewController:tmp actionType:^(NSInteger actionType) {
        
    } channel:^(NSString *channel) {
        
    }];
    [self presentViewController:shareVC animated:NO completion:nil];
}

#pragma mark - <UIDocumentMenuDelegate> 文件选择
- (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
{
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
    [controller dismissViewControllerAnimated:YES completion:nil];
    [self upLoadFile:url];
}

-(void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
{
}

-(void)upLoadFile:(NSURL *)fileUrl
{
    NSString * string_iCloud = fileUrl.absoluteString.stringByRemovingPercentEncoding;
    NSArray * stringArr = [string_iCloud componentsSeparatedByString:@"/"];
    NSString * pathString = stringArr.lastObject;
    NSString * pathLocal = [SEGWebViewLoadManager getLocalPathByPath:pathString];
    
    SEGDocument *doc =[[SEGDocument alloc] initWithFileURL:fileUrl];
    
    [doc openWithCompletionHandler:^(BOOL success) {
        if (success) {
            // 读取数据成功
            BOOL LimitOk = YES;
            long long MaxMB = 5 * 1024 * 1024;//大小限制5M
            if (doc.myData.length > MaxMB) {
                [SEGAlertView showTmepMessageWithMessage:[NSString stringWithFormat:@"选择的文件大小不可超过%dMB，请重新选择",5]];
                LimitOk = NO;
            }
            if(!LimitOk){
                return;
            }
            
            BOOL isSave = [doc.myData writeToFile:pathLocal atomically:YES];
            if (isSave) {
                // 保存入本地成功
                __block NSMutableArray<NSString*>* tmp = [NSMutableArray array];
                [tmp addObject:pathLocal];
                if (tmp.count <= 0) return;
                
                NSDictionary *params = @{
                    @"code": @"1",
                    @"message": @"",
                    @"data": tmp //本地文件路径，数组
                };
                
                SEGUrlparamsModel * js = [SEGUrlparamsModel yy_modelWithJSON:[[self.current_uhomeoc_href.query stringByURLDecode] stringByReplacingOccurrencesOfString:@"params=" withString:@""]];
                NSString *javaScript = [NSString stringWithFormat:@"%@(%@);",js.fn,[params yy_modelToJSONString]];
                [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                    
                }];
            }
            
        }
    }];
}

#pragma mark - <UIActionSheetDelegate> 用于相册的选择
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:{ //相册
            [self seg_UsePhotoAlbum:maxPhoto];
            break;
        }
        case 1:{ //相机
            [self seg_UseCamera];
            break;
        }
        default:
            break;
    }
}

#pragma mark - <SEGImagePickerManagerDelegate>
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager didFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray<PHAsset *> *)assets isSelectOriginalPhoto:(BOOL)isSelect {
    [self saveImageToLocal:photos];
}

- (void)seg_imagePickerManagerDidCancel:(SEGImagePickerManager *)picker {
    
}
@end
